/* eslint-disable react-hooks/exhaustive-deps */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * Generated with the TypeScript template
 * https://github.com/react-native-community/react-native-template-typescript
 *
 * @format
 */

import {useInterval, useThrottleFn} from 'ahooks';
import React, {useEffect, useRef, useState} from 'react';
import {
  Image,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {RNCamera} from 'react-native-camera';
import * as Brightness from 'expo-brightness';
import { Dimensions } from 'react-native';
import ResultDisplay from './DisplayResult/ResultDisplay';
import { uploadRequest } from "./src/utils/UploadUtils";

const screenWidth = Math.round(Dimensions.get('window').width);
const screenHeight = Math.round(Dimensions.get('window').height);

const App: React.FC = () => {
  const [image, setImage] = useState<string>();
  const [hideCamera, setHideCamera] = useState<boolean>(true);
  const [brightness, setBrightness] = useState<number>(1);
  const [interval, setInterval] = useState<number | null>(5000);

  const permissionsGranted = React.useRef(false);
  const [isDisplayResult, setIsDisplayResult] = useState(false);
  const [result, setResult] = useState<any>([]);

  const displayTipsCallback = (res:any)=>{
    console.log('result', res)
    if(res) {
      setResult(res);
    } else {
      setResult(undefined)
    }
    setIsDisplayResult(true);
  }
  // const [status, requestPermission] = Brightness.usePermissions();
  useEffect(() => {
    (async () => {
      try {
        let permissions = await Brightness.getPermissionsAsync();
        console.log('permissions', permissions);

        if (permissions.status !== 'granted' && permissions.canAskAgain) {
          permissions = await Brightness.requestPermissionsAsync();
          console.log('permissions-second', permissions);
        }
        if (permissions.status === 'granted') {
          permissionsGranted.current = true;
          setHideCamera(false);
          Brightness.setSystemBrightnessAsync(brightness);
        }
      } catch (error) {
        console.log('error', error);
      }
      return () => {
        if (permissionsGranted.current) {
          Brightness.setSystemBrightnessAsync(brightness);
        }
      };
    })();
  }, []);

  // useInterval(() => {
  //   takePicture();
  // }, interval);

  const brighten = async () => {
  	setBrightness(1);
  	setHideCamera(false);
		Brightness.setSystemBrightnessAsync(0.9);
  }

  const cameraRef = useRef<RNCamera>(null);
  const takePicture = async () => {
    if (cameraRef) {
      const result = await cameraRef.current?.takePictureAsync();
      if (result) {
        const {uri} = result;
        console.log(uri);
        setImage(uri);
        setIsDisplayResult(false);
        uploadRequest(uri,displayTipsCallback);
      }
    }
  };
  const {run: takePictureThrottle} = useThrottleFn(
    () => {
      takePicture();
    },
    {wait: 1000},
  );
  return (
    <ScrollView style={styles.screen}>
      {
        isDisplayResult && <ResultDisplay result={result} />
      }
			{
				brightness == 1 ?
					<View>
						<SafeAreaView style={styles.saveArea}>
							<View style={styles.topBar}>
								<Text>Awesome Garbage Classification</Text>
							</View>
						</SafeAreaView>
						<View style={styles.caption}>
							<Text>Please Put your garbage in front of the camera</Text>
						</View>
						{hideCamera || (
							<RNCamera style={styles.rnCamera} type="back" ref={cameraRef} />
						)}
						<View style={styles.control}>
							<TouchableOpacity
								style={styles.btn}
								onPress={() => {
									setHideCamera(false);
									Brightness.setBrightnessAsync(1);
								}}>
								<Text style={styles.btnText}>OpenCamera</Text>
							</TouchableOpacity>
							<TouchableOpacity
								style={styles.btn}
								onPress={() => {
									Brightness.setBrightnessAsync(0);
									setBrightness(0);
									setHideCamera(true);
								}}>
								<Text style={styles.btnText}>changeBrightness</Text>
							</TouchableOpacity>
						</View>

						<View style={styles.imageView}>
							<Image
								source={{
									height: 600,
									width: 350,
									uri: image,
								}}
							/>
						</View>
					</View>
				:
				<View>
					<TouchableOpacity style={styles.fullScreenTouchable} activeOpacity={1} onPress={brighten}>
						<Text>Please click the screen to continue</Text>
					</TouchableOpacity>
				</View>
			}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  screen: {
    // flex: 1,
    backgroundColor: '#F2F2FC',
    // justifyContent: 'space-between',
  },
  saveArea: {
    backgroundColor: '#464775',
  },
  topBar: {
    height: 50,
    backgroundColor: '#464775',
    alignItems: 'center',
    justifyContent: 'center',
  },
  caption: {
    height: 120,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 30,
  },
  control: {
    height: 180,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  rnCamera: {
    width: 300,
    height: 300,
    alignSelf: 'center',
    marginBottom: 30,
  },
  btn: {
    flex: 1,
    height: 50,
    borderRadius: 4,
    backgroundColor: '#62d1bc',
    paddingHorizontal: 24,
    paddingVertical: 12,
    marginVertical: 8,
    marginLeft: 10,
  },
  btnText: {
    fontSize: 14,
    color: '#ffffff',
    textAlign: 'center',
    lineHeight: 14,
  },
  imageView: {
    // width: '100%',
    // height: 200,
    color: '#ffffff',
    alignItems: 'center',
  },
  fullScreenTouchable: {
  	alignItems: 'center',
		justifyContent: 'center',
		width: screenWidth,
		height: screenHeight,
		fontSize: 50
  }
});

export default App;
